package com.wx.mall.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wx.mall.common.exception.BusinessException;
import com.wx.mall.common.exception.code.BrandResponseCode;
import com.wx.mall.common.utils.UploadUtil;
import com.wx.mall.common.vo.goods.BrandBaseVo;
import com.wx.mall.goods.entity.Brand;
import com.wx.mall.goods.mapper.BrandMapper;
import com.wx.mall.goods.service.IBrandService;
import com.wx.mall.goods.util.InitialGenerator;
import com.wx.mall.goods.vo.req.BrandBatchReqVO;
import com.wx.mall.goods.vo.req.BrandPageReqVO;
import com.wx.mall.goods.vo.req.BrandReqVO;
import com.wx.mall.goods.vo.req.PageReqVO;
import com.wx.mall.goods.vo.resp.BrandRespVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 品牌服务实现类
 * </p>
 *
 * @author ljl
 * @since 2020-03-17
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

    /**
     * 文件上传路径
     */
    @Value("${localhost.file.path}")
    private String filePath;
    @Autowired
    private UploadUtil uploadUtil;

    @Override
    public Page<Brand> pageInfo(BrandPageReqVO vo) {
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        wrapper.eq("del_state", "0");
        Page<Brand> page = new Page<Brand>(vo.getPageNum(), vo.getPageSize());
//        //分页结果页面
//        Page<Brand> brandPage = null;
        //排序方式
        int sort = vo.getSort();
        if (sort == 0) {// 0 编号
            wrapper.orderByAsc("id");
        } else if (sort == 1) {// 1 名称
            wrapper.orderByAsc("name");
        } else if (sort == 2) {// 2 首字母
            wrapper.orderByAsc("initial");
        }

        return baseMapper.selectPage(page, wrapper);
    }

    @Override
    public List<BrandRespVO> availableInfos() {
        List<BrandRespVO> list = new ArrayList<>();

        // mybatis-plus 条件查询
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        // 所有未删数据
        wrapper.eq("del_state", "0");
        List<Brand> templates = baseMapper.selectList(wrapper);

        for (Brand template : templates){
            BrandRespVO vo = new BrandRespVO();
            //将CarriageTemplate实体中的数据复制到vo中
            BeanUtils.copyProperties(template, vo);
            list.add(vo);
        }
        return list;
    }

    @Override
    public List<BrandBaseVo> listBaseAvailable() {
        List<BrandBaseVo> list = new ArrayList<>();

        // mybatis-plus 条件查询
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        // 所有未删数据
        wrapper.eq("del_state", "0");
        for (Brand brand : this.list(wrapper)){
            BrandBaseVo vo = new BrandBaseVo();
            //将brand实体中的数据复制到vo中
            BeanUtils.copyProperties(brand, vo);
            list.add(vo);
        }
        return list;
    }

    @Override
    public Page<Brand> pageList(BrandPageReqVO vo) {
        Page<Brand> page = new Page<Brand>(vo.getPageNum(), vo.getPageSize());
        //分页结果页面
        Page<Brand> brandPage = null;
        //排序方式
        int sort = vo.getSort();
        if (sort == 0) {// 0 编号
            brandPage = baseMapper.selectPage(page, new QueryWrapper<Brand>().orderByAsc("id"));
        } else if (sort == 1) {// 1 名称
            brandPage = baseMapper.selectPage(page, new QueryWrapper<Brand>().orderByAsc("name"));
        } else if (sort == 2) {// 2 首字母
            brandPage = baseMapper.selectPage(page, new QueryWrapper<Brand>().orderByAsc("initial"));
        }

        return brandPage;
    }

    @Override
    public Page<Brand> pageMatch(BrandPageReqVO vo) {
        // mybatis-plus 条件查询
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();

        Page<Brand> page = new Page<Brand>(vo.getPageNum(), vo.getPageSize());
        //分页结果页面
        Page<Brand> brandPage = null;
        // 如果name为null 设置name为""
//        if (vo.getMatchName() == null){
//            vo.setMatchName("");
//        }
        // 代码优化方式
        if (vo.getMatchName() != null){
            wrapper.like("name", vo.getMatchName());
        }
        //排序方式
        int sort = vo.getSort();
        if (sort == 0) {// 0 编号
            wrapper.orderByAsc("id");
        } else if (sort == 1) {// 1 名称
            wrapper.orderByAsc("name");
        } else if (sort == 2) {// 2 首字母
            wrapper.orderByAsc("initial");
        }

        brandPage = baseMapper.selectPage(page, wrapper);

        return brandPage;
    }

    @Override
    public Page<Brand> initialGenerator(PageReqVO vo) {
        Page<Brand> page = new Page<Brand>(vo.getPageNum(), vo.getPageSize());
        Page<Brand> brandPage = baseMapper.selectPage(page,null);
        List<Brand> records = brandPage.getRecords();
        for (Brand brand : records) {
            if ("".equals(brand.getInitial())) {
                String name = brand.getName();
                String upperCase = InitialGenerator.getPinYinHeadChar(String.valueOf(name.charAt(0))).toUpperCase();
                brand.setInitial(upperCase);
                baseMapper.updateById(brand);
            }
        }

        brandPage = baseMapper.selectPage(page, null);
        return brandPage;
    }

    @Override
    public void softDeleteById(Integer id) {
        Map<String, Object> params = new HashMap<>();
        params.put("state", "1");
        params.put("id", id);
        int result = baseMapper.updateStateById(params);
        if (result == 0) {
            throw new BusinessException(BrandResponseCode.DELETE_ERROR);
        }
    }

    @Override
    public void batchOperation(BrandBatchReqVO vo) {
        Map<String, Object> params = new HashMap<>();
        // 操作是否有效
        Integer isEnabled = 0;
        // 要执行什么操作 0 修改（还原） 1 删除
        if (vo.getType() == 1) {
            params.put("state", "1");
            isEnabled = 1;
        } else if (vo.getType() == 0){
            params.put("state", "0");
            isEnabled = 1;
        }

        if (isEnabled == 1) {
            for (Integer id : vo.getIds()) {
                params.put("id", id);
                baseMapper.updateStateById(params);
            }
        }
    }

    @Override
    public Brand findById(Integer id) {
        Brand brand = baseMapper.selectOne(new QueryWrapper<Brand>().eq("id", id));
        if (brand == null) {
            throw new BusinessException(BrandResponseCode.QUERY_ERROR);
        }
        return brand;
    }

    @Override
    public void updateById(BrandReqVO vo) {
        Brand brand = new Brand();
        //将vo中的数据复制到实体类中
        BeanUtils.copyProperties(vo, brand);
        //如果首字母为空
        if (vo.getInitial() == null) {
            brand.setInitial("");
        }
        // 更新数据后 重新设置为可用状态
        if ("1".equals(brand.getDelState())) {
            brand.setDelState("0");
        }
        Integer result = baseMapper.updateById(brand);
        if (result == 0) {
            throw new BusinessException(BrandResponseCode.UPDATE_ERROR);
        }
    }

    @Override
    public void add(BrandReqVO vo) {
        Brand brand = new Brand();
        //将vo中的数据复制到实体类中
        BeanUtils.copyProperties(vo, brand);
        brand.setDelState("0");
        if (brand.getInitial() == null) {
            brand.setInitial("");
        }
        Integer result = baseMapper.insert(brand);
        if (result == 0) {
            throw new BusinessException(BrandResponseCode.INSERT_ERROR);
        }
    }

    @Override
    public Map<String, String> uploadLogo(MultipartFile file, String name) {
        return uploadUtil.uploadMD5(file,filePath,name+"_logo");
    }


}
